package com.media.publish;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baselibrary.Constants;
import com.baselibrary.MessageBus;
import com.baselibrary.activity.BaseActivity;
import com.baselibrary.manager.CityManager;
import com.baselibrary.permission.PermissionCollection;
import com.baselibrary.permission.PermissionsUtils;
import com.baselibrary.permission.callback.PermissionsCall;
import com.baselibrary.utils.CommonUtil;
import com.baselibrary.utils.ContextUtils;
import com.baselibrary.utils.EventBusUtils;
import com.baselibrary.utils.KeyBoardUtils;
import com.baselibrary.utils.SpUtils;
import com.baselibrary.utils.SpringViewNewFooter;
import com.baselibrary.utils.SpringViewNewHeader;
import com.baselibrary.utils.ToastUtils;
import com.liaoinstan.springview.widget.SpringView;
import com.media.R;
import com.media.databinding.ActivityAmapLocationBinding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import com.media.publish.adapter.LocationAdapter;
import com.media.publish.utils.BaiduMapUtils;

public class BaiduMapLocationActivity extends BaseActivity implements View.OnClickListener, OnGetPoiSearchResultListener, OnGetGeoCoderResultListener {
    private ActivityAmapLocationBinding mBinding;
    private LocationAdapter adapter;
    private String searchStr;
    private boolean isRefresh = false;

    private int currentPage = 1;// 当前页面，从0开始计数
    private PoiSearch poiSearch;
    private GeoCoder geocoder;
    private List<PoiInfo> poiItems = new ArrayList<>();// poi数据
    private LocationClient mLocationClient;
    public String cityName = "";
    public String provinceName = "";
    public String cityId = "";
    public String provinceId = "";
    @Override
    protected int getLayoutId() {
        return R.layout.activity_amap_location;
    }

    @Override
    protected void init() {
        mBinding = getDataBinding();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        SDKInitializer.setAgreePrivacy(ContextUtils.getCurApplication(), true);
        SDKInitializer.initialize(ContextUtils.getCurApplication());
        poiSearch = PoiSearch.newInstance();
        geocoder = GeoCoder.newInstance();

        poiSearch.setOnGetPoiSearchResultListener(this);
        geocoder.setOnGetGeoCodeResultListener(this);
        mBinding.tvSearchLocationCancel.setOnClickListener(this);
        mBinding.searchContentDelete.setOnClickListener(this);
        checkLocationPermission();
        mBinding.svLocationList.setHeader(new SpringViewNewHeader(getApplicationContext()));
        mBinding.svLocationList.setFooter(new SpringViewNewFooter(getApplicationContext()));
        mBinding.svLocationList.setType(SpringView.Type.FOLLOW);
        mBinding.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isRefresh = true;
                initSearchView(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mBinding.etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String content = mBinding.etSearch.getText().toString().trim();
                    if (!CommonUtil.isBlank(content)) {
                        KeyBoardUtils.hideShowKeyboard(BaiduMapLocationActivity.this);
                        isRefresh = true;
                        initSearchView(content);
                    } else {
                        ToastUtils.showShort(BaiduMapLocationActivity.this, "请输入搜索关键字");
                    }
                    return true;
                }
                return false;
            }
        });

        adapter = new LocationAdapter();
        View inflate = LayoutInflater.from(this).inflate(R.layout.view_dynamic_search_location, null);
        adapter.addHeaderView(inflate);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            Object o = adapter.getData().get(position);
            if (o instanceof PoiInfo) {
                Intent intent = new Intent();
                intent.putExtra("location", (PoiInfo) o);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        initSearchView("");

        mBinding.svLocationList.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                isRefresh = true;
                doSearchQuery(searchStr);
            }

            @Override
            public void onLoadmore() {
                if (TextUtils.isEmpty(searchStr)) {
                    mBinding.svLocationList.onFinishFreshAndLoad();
                } else {
                    currentPage += 1;
                    isRefresh = false;
                    doSearchQuery(searchStr);
                }
            }
        });
        inflate.setOnClickListener(view -> {
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
            finish();
        });
    }

    private void initSearchView(String searchStr) {
        this.searchStr = searchStr;
        currentPage = 1;
        mBinding.searchContentDelete.setVisibility(CommonUtil.isBlank(searchStr) ? View.GONE : View.VISIBLE);
        doSearchQuery(searchStr);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_searchLocation_cancel) {
            finish();
        } else if (id == R.id.search_content_delete) {
            mBinding.etSearch.setText("");
        }
    }


    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String keyWord) {
        double lat_s = SpUtils.getFloat(ContextUtils.getCurApplication(), "address_Lat", 0);
        double log_s = SpUtils.getFloat(ContextUtils.getCurApplication(), "address_long", 0);
        if (TextUtils.isEmpty(keyWord)) {
            geocoder.reverseGeoCode(new ReverseGeoCodeOption()
                    .location(new LatLng(lat_s, log_s))
                    .newVersion(1)
                    .radius(1000));
        } else {
            poiSearch.searchNearby(new PoiNearbySearchOption()
                    .location(new LatLng(lat_s, log_s))
                    .radius(5000).keyword(keyWord)
                    .pageNum(currentPage).pageCapacity(20));
        }
    }

    //创建监听权限的接口对象
    private PermissionsCall permissionsResult = new PermissionsCall() {

        @Override
        public void permissionsPass() {
            initLocation();
        }
    };

    //检查定位权限
    private void checkLocationPermission() {
        //权限未通过
        PermissionsUtils.getInstance().chekPermissions(this, PermissionCollection.LOCATION.getPermissionList(), permissionsResult);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageBus messageBus) {
    }

    private void initLocation() {
        try {
            LocationClient.setAgreePrivacy(true);
            mLocationClient = new LocationClient(BaiduMapLocationActivity.this);
            BaiduMapUtils.INSTANCE.getLocationInfo(mLocationClient, new BDAbstractLocationListener() {
                @Override
                public void onReceiveLocation(BDLocation bdLocation) {
                    if (bdLocation != null) {
                        //定位成功回调信息，设置相关消息
                        cityName = bdLocation.getCity();
                        provinceName = bdLocation.getProvince();
                        cityId = CityManager.getInstance().gtCityId(provinceName, cityName);
                        provinceId = CityManager.getInstance().gtProvinceId(provinceName);
                        SpUtils.putString(ContextUtils.getCurApplication(), "province_id", provinceId);
                        SpUtils.putString(ContextUtils.getCurApplication(), "city_id", cityId);
                        SpUtils.putFloat(ContextUtils.getCurApplication(), "address_Lat", (float) (bdLocation.getLatitude()));
                        SpUtils.putFloat(ContextUtils.getCurApplication(), "address_long", (float) (bdLocation.getLongitude()));
                        SpUtils.putString(ContextUtils.getCurApplication(), "address_ProvinceName", bdLocation.getProvince());
                        SpUtils.putString(ContextUtils.getCurApplication(), "address_CityName", bdLocation.getCity());
                        SpUtils.putString(ContextUtils.getCurApplication(), "address_AreaName", bdLocation.getDistrict());
                        SpUtils.putString(ContextUtils.getCurApplication(), "address_Town", bdLocation.getTown());
                        //在其他地方开启定位权限时，给附件酒窖顶部地址赋值
                        SpUtils.putString(ContextUtils.getCurApplication(), Constants.KEY_WINERY_SELECT_ADRES, bdLocation.getPoiRegion() != null ? bdLocation.getPoiRegion().getName() : bdLocation.getStreet());
                        if (bdLocation.getPoiRegion() != null) {
                            SpUtils.putString(ContextUtils.getCurApplication(), "address_Region", bdLocation.getPoiRegion().getName());
                        }
                        initSearchView("");
                        mLocationClient.stop();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (poiSearch != null) {
            poiSearch.destroy();
        }
        if (geocoder != null) {
            geocoder.destroy();
        }
        super.onDestroy();
    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        mBinding.svLocationList.onFinishFreshAndLoad();
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            if (result.getAllPoi() != null) {// 搜索poi的结果
                poiItems = result.getAllPoi();// 取得第一页的poiitem数据，页数从数字0开始
                List<CityInfo> suggestionCities = result.getSuggestCityList();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                if (poiItems != null && poiItems.size() > 0) {
                    mBinding.tvSearchlocationEmpty.setVisibility(View.GONE);
                    mBinding.svLocationList.setVisibility(View.VISIBLE);
                    adapter.setSearchStr(searchStr);
                    if (isRefresh) {
                        adapter.setNewData(poiItems);
                    } else {
                        adapter.addData(poiItems);
                    }
                } else if (suggestionCities != null && suggestionCities.size() > 0) {
                    mBinding.svLocationList.onFinishFreshAndLoad();
                    ToastUtils.showShort(this,"已经全部加载完成");
                    mBinding.tvSearchlocationEmpty.setVisibility(View.GONE);
                    mBinding.svLocationList.setVisibility(View.VISIBLE);
                } else {
                    if (currentPage == 1) {//因为上拉加载的时候，会走到这里 根据currentPage判断是否是第一页，第一页走到这里说明没有数据
                        mBinding.tvSearchlocationEmpty.setVisibility(View.VISIBLE);
                        mBinding.svLocationList.setVisibility(View.GONE);
                    } else if (currentPage > 1) {
                        ToastUtils.showShort(this,"已经全部加载完成");
                        mBinding.tvSearchlocationEmpty.setVisibility(View.GONE);
                        mBinding.svLocationList.setVisibility(View.VISIBLE);
                    }
                }
            }
        } else if (result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            mBinding.tvSearchlocationEmpty.setVisibility(View.VISIBLE);
            mBinding.svLocationList.setVisibility(View.GONE);
        } else {
            adapter.setNewData(new ArrayList<>());
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        mBinding.svLocationList.onFinishFreshAndLoad();
        if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            //没有找到检索结果
            return;
        } else {
            poiItems = reverseGeoCodeResult.getPoiList();
            if (poiItems != null && poiItems.size() > 0) {
                mBinding.tvSearchlocationEmpty.setVisibility(View.GONE);
                mBinding.svLocationList.setVisibility(View.VISIBLE);
                adapter.setSearchStr("");
                if (isRefresh) {
                    adapter.setNewData(poiItems);
                } else {
                    adapter.addData(poiItems);
                }
            }
        }
    }
}